package com.ma5d.driver.driver.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ma5d.driver.common.constant.SystemConstant;
import com.ma5d.driver.driver.mapper.DriverAccountMapper;
import com.ma5d.driver.driver.mapper.DriverInfoMapper;
import com.ma5d.driver.driver.mapper.DriverLoginLogMapper;
import com.ma5d.driver.driver.mapper.DriverSetMapper;
import com.ma5d.driver.driver.properties.TencentProperties;
import com.ma5d.driver.driver.service.DriverInfoService;
import com.ma5d.driver.model.entity.driver.DriverAccount;
import com.ma5d.driver.model.entity.driver.DriverInfo;
import com.ma5d.driver.model.entity.driver.DriverLoginLog;
import com.ma5d.driver.model.entity.driver.DriverSet;
import com.ma5d.driver.model.form.DriverFaceModelForm;
import com.ma5d.driver.model.form.UpdateDriverAuthInfoForm;
import com.ma5d.driver.model.vo.driver.DriverLoginVo;
import com.tencentcloudapi.iai.v20180301.models.CreatePersonRequest;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.iai.v20180301.IaiClient;
import com.tencentcloudapi.iai.v20180301.models.CreatePersonResponse;
import jakarta.annotation.Resource;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

@Service
public class DriverInfoServiceImpl extends ServiceImpl<DriverInfoMapper, DriverInfo> implements DriverInfoService {

    @Resource
    private WxMaService wxMaService;

    @Resource
    private DriverInfoMapper driverInfoMapper;

    @Resource
    private DriverSetMapper driverSetMapper;

    @Resource
    private DriverAccountMapper driverAccountMapper;

    @Resource
    private DriverLoginLogMapper driverLoginLogMapper;

    @Resource
    private TencentProperties tencentProperties;

    @Override
    public Long login(String code) throws WxErrorException {
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        String openId = sessionInfo.getOpenid();
        LambdaQueryWrapper<DriverInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DriverInfo::getWxOpenId, openId);
        DriverInfo driverInfo = driverInfoMapper.selectOne(wrapper);
        if (driverInfo == null) {
            // 添加司机基本信息
            driverInfo = new DriverInfo();
            driverInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            driverInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            driverInfo.setWxOpenId(openId);
            driverInfoMapper.insert(driverInfo);

            DriverSet driverSet = new DriverSet();
            driverSet.setDriverId(driverInfo.getId());
            driverSet.setOrderDistance(new BigDecimal(0));
            driverSet.setAcceptDistance(new BigDecimal(SystemConstant.ACCEPT_DISTANCE));
            driverSet.setIsAutoAccept(0);
            driverSetMapper.insert(driverSet);

            // 初始化司机账户信息
            DriverAccount driverAccount = new DriverAccount();
            driverAccount.setDriverId(driverInfo.getId());
            driverAccountMapper.insert(driverAccount);
        }

        // 记录司机的登录信息
        DriverLoginLog driverLoginLog = new DriverLoginLog();
        driverLoginLog.setDriverId(driverInfo.getId());
        driverLoginLog.setMsg("小程序登录");
        driverLoginLogMapper.insert(driverLoginLog);

        // 返回司机id
        return driverInfo.getId();
    }

    @Override
    public DriverLoginVo getDriverLoginInfo(String driverId){
        // 根据司机 id 获取司机信息
        DriverInfo driverInfo = driverInfoMapper.selectById(driverId);

        // driverInfo -- DriverLoginVo
        DriverLoginVo driverLoginVo = new DriverLoginVo();
        BeanUtils.copyProperties(driverInfo,driverLoginVo);

        // 是否建档人脸识别
        String faceModelId = driverInfo.getFaceModelId();
        boolean isArchiveFace = StringUtils.hasText(faceModelId);

        driverLoginVo.setIsArchiveFace(isArchiveFace);
        return driverLoginVo;
    }

    @Override
    public Boolean updateDriverAuthInfo(UpdateDriverAuthInfoForm updateDriverAuthInfoForm) {
        Long driverId = updateDriverAuthInfoForm.getDriverId();
        DriverInfo driverInfo = new DriverInfo();
        driverInfo.setId(driverId);
        BeanUtils.copyProperties(updateDriverAuthInfoForm,driverInfo);
        return this.updateById(driverInfo);
    }

    @Override
    public Boolean createDriverFaceModel(DriverFaceModelForm driverFaceModelForm) {
        DriverInfo driverInfo = driverInfoMapper.selectById(driverFaceModelForm.getDriverId());
        try{
            Credential credential = new Credential(tencentProperties.getSecretId(), tencentProperties.getSecretKey());
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("iai.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            IaiClient iaiClient = new IaiClient(credential, tencentProperties.getRegion(), clientProfile);
            CreatePersonRequest request = new CreatePersonRequest();
            request.setGroupId(tencentProperties.getPersonGroupId());
            request.setPersonId(String.valueOf(driverInfo.getId()));
            request.setGender(Long.valueOf(driverInfo.getGender()));
            request.setQualityControl(4L);
            request.setUniquePersonControl(4L);
            request.setPersonName(driverInfo.getName());
            request.setImage(driverFaceModelForm.getImageBase64());
            // CreatePersonResponse response = iaiClient.CreatePerson(request);
            // System.out.println(AbstractModel.toJsonString(response));
            // language=json
            String json = """
                    {
                      "FaceId": "6071615352163321784",
                      "FaceModelVersion": "3.0",
                      "FaceRect": {
                        "Height": 618,
                        "Width": 446,
                        "X": 126,
                        "Y": 191
                      },
                      "RequestId": "eb4a3926-964a-4591-8ca9-4008059281c7",
                      "SimilarPersonId": ""
                    }
                    """;
            CreatePersonResponse response = JSON.parseObject(json, CreatePersonResponse.class);
            // {"FaceId":"6071615352163321784","FaceRect":{"X":126,"Y":191,"Width":446,"Height":618},"SimilarPersonId":"","FaceModelVersion":"3.0","RequestId":"eb4a3926-964a-4591-8ca9-4008059281c7"}
            // {"FaceId":"6071615352163321784","FaceModelVersion":"3.0","FaceRect":{"Height":618,"Width":446,"X":126,"Y":191},"RequestId":"eb4a3926-964a-4591-8ca9-4008059281c7","SimilarPersonId":""}
            String faceId = response.getFaceId();
            if(StringUtils.hasText(faceId)){
                driverInfo.setFaceModelId(faceId);
                driverInfoMapper.updateById(driverInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
